import HeaderNav from "@/components/header-nav";
import FooterNav from "@/components/footer-nav";
import { Grid, Image, Modal, Button, Dialog, Tag } from "antd-mobile";
import { showSuccessToast } from '@/utils/customToast';
import {
  BillOutline,
  BankcardOutline,
  FillinOutline,
  FileOutline,
  QuestionCircleOutline,
  AlipayCircleFill,
  ChatCheckOutline,
  HandPayCircleOutline,
  CheckCircleFill,
} from "antd-mobile-icons";
import styles from "./index.module.less";
import classNames from "classnames";
import { useEffect, useState } from "react";
const {
  getGoodsList,
  getGoodsPays,
  getDiamondRechargePlan,
  getUserInfo,
  getMemberLevel,
  getMemberLevelList,
  getCommonSettingsByKeys,
} = $globalServicer("My");

const My = () => {
  const [goodsList, setGoodsList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [payVisible, setPayVisible] = useState(false);
  const [vipContent, setVipContent] = useState("");
  const [goodsPayInfo, setGoodsPayInfo] = useState(null);
  const [memberLevel, setMemberLevel] = useState([]);
  const [limitMemberLevel, setLimitMemberLevel] = useState([]);
  const customNavigate = $globalNavigate();
  const [payMethod, setPayMethod] = useState("hupijiao_wx");
  const [userInfo, setUserInfo] = useState(null);
  const [selectedType, setSelectedType] = useState(null); // 'diamond' 或 'vip'
  const [memberLevelList, setMemberLevelList] = useState([]);
  const [rechargeInstruction, setRechargeInstruction] = useState("");

  const fetchDiamondRechargePlanList = () => {
    getDiamondRechargePlan().then((res) => {
      setGoodsList(res);
    });
  };

  const openUrl = (url) => {
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    if (isMobile) {
      window.location.href = url;
    } else {
      window.open(url, "_blank");
    }
  };

  const fetchUserInfo = () => {
    getUserInfo().then((res) => {
      setUserInfo(res);
    });
  };

  const fetchMemberLevel = () => {
    // 获取限时会员数据 (type: 2)
    getMemberLevel({ type: 2 }).then((res) => {
      console.log('限时会员数据:', res);
      const _res = res.map((f) => {
        if (f?.benefits?.length && f?.benefits.indexOf("\r\n")) {
          f.benefits = f.benefits.split("\r\n");
        } else {
          f.benefits = [f.benefits];
        }
        return f;
      });
      setMemberLevel(_res);
    }).catch(error => {
      console.error('获取限时会员数据失败:', error);
    });

    // 获取超级会员数据 (type: 1) - 用于其他功能
    getMemberLevel({type: 1}).then((res) => {
      console.log('超级会员数据:', res);
      const _res = res.map((f) => {
        if (f?.benefits?.length && f?.benefits.indexOf("\r\n")) {
          f.benefits = f.benefits.split("\r\n");
        } else {
          f.benefits = [f.benefits];
        }
        return f;
      });
      setLimitMemberLevel(_res);
    }).catch(error => {
      console.error('获取超级会员数据失败:', error);
    });

    getMemberLevelList().then((res) => {
      console.log('会员等级列表:', res);
      setMemberLevelList(res);
    }).catch(error => {
      console.error('获取会员等级列表失败:', error);
    });
  };

  const fetchRechargeInstruction = () => {
    getCommonSettingsByKeys("recharge_instruction").then((res) => {
      
      if (res && res.value) {
        setRechargeInstruction(res.value);
      } else {
        // 如果接口返回成功但没有数据，使用默认的充值须知
        setRechargeInstruction("1. 充值成功后，梦钥将3-5s后到账\n2. 梦钥可用于与AI角色进行对话\n3. 如有疑问，请联系客服\n4. 虚拟商品，已经售出概不退换");
      }
    }).catch(error => {
      // 如果接口调用失败，使用默认的充值须知
      setRechargeInstruction("1. 充值成功后，梦钥将3-5s后到账\n2. 梦钥可用于与AI角色进行对话\n3. 如有疑问，请联系客服\n4. 虚拟商品，已经售出概不退换");
    });
  };

  useEffect(() => {
    fetchUserInfo();
    fetchMemberLevel();
    fetchDiamondRechargePlanList();
    fetchRechargeInstruction();
  }, []);

  // 计算当前选择的支付金额和展示文本
  const getPaymentInfo = () => {
    if (selectedType === "vip") {
      if (goodsPayInfo.type === 1) {
        return {
          amount: memberLevel.find((item) => item.id === goodsPayInfo.id)?.price,
          text: `开通超级会员`,
        };
      } else if (goodsPayInfo.type === 2) {
        return {
          amount: limitMemberLevel.find((item) => item.id === goodsPayInfo.id)?.price,
          text: `开通限时会员`,
        };
      }
    } else if (selectedType === "diamond") {
      const selectedGoods = goodsList.find((item) => item.id === goodsPayInfo.id);
      const price = selectedGoods?.pay_price
        ? selectedGoods?.pay_price
        : selectedGoods?.price || 0;
      return {
        amount: price,
        text: `获得${selectedGoods?.diamond_amount || 0}梦钥`,
      };
    }
    return { amount: 0, text: "" };
  };

  // 渲染充值须知
  const renderRechargeInstruction = () => {
    if (!rechargeInstruction) {
      return (
        <div className={styles.pointsUsageCard}>
          <p className={styles.infoTitle}>充值须知：</p>
          <p>加载中...</p>
        </div>
      );
    }

    // 解析HTML标签并渲染
    const parseHtmlContent = (htmlString) => {
      console.log('解析HTML内容，原始字符串:', htmlString);
      
      // 先将各种结束标签替换为换行符，保留段落分隔
      let textContent = htmlString
        .replace(/<\/p>/g, '\n')
        .replace(/<\/div>/g, '\n')
        .replace(/<\/br>/g, '\n')
        .replace(/<br\s*\/?>/g, '\n');
      console.log('处理段落标签后的文本:', textContent);
      
      // 移除所有HTML标签，只保留文本内容
      textContent = textContent.replace(/<[^>]*>/g, '');
      console.log('移除HTML标签后的文本:', textContent);
      
      // 处理HTML实体，将&nbsp;替换为普通空格
      textContent = textContent
        .replace(/&nbsp;/g, ' ')
        .replace(/&amp;/g, '&')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'");
      console.log('处理HTML实体后的文本:', textContent);
      
      // 清理多余的换行符，但保留换行符
      textContent = textContent.replace(/\n\s*\n/g, '\n');
      // 清理每行内部的多余空格，但保留换行符
      textContent = textContent.replace(/[^\S\n]+/g, ' ');
      
      // 按换行符分割并过滤空行
      const instructions = textContent.split('\n').filter(instruction => instruction.trim());
      console.log('分割后的说明项:', instructions);
      
      return (
        <div className={styles.pointsUsageCard}>
          {instructions.map((instruction, index) => (
            <p key={index}>{instruction}</p>
          ))}
        </div>
      );
    };
    
    return parseHtmlContent(rechargeInstruction);
  };

  const hanldePay = (pay) => {
    console.log("🚀 ~ hanldePay ~ pay:", pay);
    
    // 使用传递的参数或状态中的值
    const currentSelectedType = pay.selectedType || selectedType;
    const currentGoodsPayInfo = pay.goodsPayInfo || goodsPayInfo;
    
    console.log("🚀 ~ hanldePay ~ currentSelectedType:", currentSelectedType);
    console.log("🚀 ~ hanldePay ~ currentGoodsPayInfo:", currentGoodsPayInfo);
    
    if (pay.key === "taobao") {
      setPayVisible(false);
      openUrl(
          "https://shop.m.taobao.com/shop/shop_index.htm?shop_id=368895194&user_id=4013292613"
      );
      return;
    }
    // 这里要对 goods_type 进行判断
    let goods_type = 0;
    if (currentSelectedType === "vip") {
      // 超级会员 1， 限时会员 3
      goods_type = currentGoodsPayInfo.type === 1 ? 1 : 3;
      console.log("🚀 ~ 会员类型判断 ~ currentGoodsPayInfo.type:", currentGoodsPayInfo.type);
      console.log("🚀 ~ 会员类型判断 ~ goods_type:", goods_type);
    } else if (currentSelectedType === "diamond") {
      // 梦钥充值
      goods_type = 2;
    }
    const data = {
      type: pay.key,
      goods_type: goods_type,
      goods_id: currentGoodsPayInfo.id,
      use_balance: pay.key === "balance",
    }
    // 这里判断一下 goodsPayInfo.is_opened 如果存在，再次购买的时候需要判断是否已经购买过
    const isInMemberLevelList = currentGoodsPayInfo.is_opened
    if (isInMemberLevelList) {
      Dialog.confirm({
        content: '您已经购买过该会员，是否继续购买？',
        cancelText: '取消',
        confirmText: '确定',
        onConfirm: () => {
          getGoodsPays(data).then((res) => {
            if (res?.pay_info?.pay_url) {
              setPayVisible(false);
              openUrl(res?.pay_info?.pay_url);
            } else {
              showSuccessToast("支付成功");
              customNavigate("/my");
            }
          });
        }
      })
    } else {
      getGoodsPays(data).then((res) => {
        if (res?.pay_info?.pay_url) {
          setPayVisible(false);
          openUrl(res?.pay_info?.pay_url);
        } else {
          showSuccessToast("支付成功");
          customNavigate("/my");
        }
      });
    }
  };

  return (
    <div className="warp">
      <div className={styles.header}>
        <HeaderNav title="充值服务" backArrow={true}></HeaderNav>
      </div>
      <div className={styles.goodsContent}>
        {/* 积分充值 */}
        <div className={styles.rechargeSection}>
          <h2 className={styles.sectionTitle}>积分充值</h2>
          <div className={styles.pointsCard}>
            <div className={styles.pointsInfo}>
              <div className={styles.pointsAmount}>
                {goodsList.length > 0 ? `${goodsList[0]?.diamond_amount?.toLocaleString() || 0} 积分` : '加载中...'}
              </div>
              <div className={styles.pointsDesc}>
                {goodsList.length > 0 ? goodsList[0]?.title || '一次性购买' : '一次性购买'}
              </div>
            </div>
            <button
              className={styles.pointsButton}
              onClick={() => {
                if (goodsList.length > 0) {
                  const goodsInfo = {
                    id: goodsList[0]?.id,
                    diamond_amount: goodsList[0]?.diamond_amount,
                    price: goodsList[0]?.price
                  };
                  setSelectedType("diamond");
                  setGoodsPayInfo(goodsInfo);
                  // 使用 setTimeout 确保状态更新后再调用支付
                  setTimeout(() => {
                    hanldePay({ key: payMethod, goods_id: goodsList[0]?.id, selectedType: "diamond", goodsPayInfo: goodsInfo });
                  }, 0);
                }
              }}
              disabled={goodsList.length === 0}
            >
              {goodsList.length > 0 ? `¥ ${goodsList[0]?.price || 0}` : '¥ 0'}
            </button>
          </div>

          {/* 如果有多个积分充值选项，显示更多选项 */}
          {goodsList.length > 1 && (
            <div className={styles.additionalPointsOptions}>
              {goodsList.slice(1).map((item, index) => (
                <div key={item.id || index} className={styles.pointsCard}>
                  <div className={styles.pointsInfo}>
                    <div className={styles.pointsAmount}>
                      {item.diamond_amount?.toLocaleString() || 0} 积分
                    </div>
                    <div className={styles.pointsDesc}>
                      {item.title || '一次性购买'}
                    </div>
                  </div>
                  <button
                    className={styles.pointsButton}
                    onClick={() => {
                      const goodsInfo = {
                        id: item.id,
                        diamond_amount: item.diamond_amount,
                        price: item.price
                      };
                      setSelectedType("diamond");
                      setGoodsPayInfo(goodsInfo);
                      setTimeout(() => {
                        hanldePay({ key: payMethod, goods_id: item.id, selectedType: "diamond", goodsPayInfo: goodsInfo });
                      }, 0);
                    }}
                  >
                    ¥ {item.price || 0}
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 会员套餐 */}
        <div className={styles.rechargeSection}>
          <h2 className={styles.sectionTitle}>会员套餐</h2>
          <div className={styles.memberCards}>
            {console.log('当前memberLevel数据:', memberLevel)}
            {memberLevel.length > 0 ? (
              memberLevel.map((member, index) => {
                // 根据会员等级确定样式类名
                const getCardStyle = (level) => {
                  switch (level) {
                    case 'UR':
                    case 'ur':
                      return styles.urCard;
                    case 'SSR':
                    case 'ssr':
                      return styles.ssrCard;
                    case 'SR':
                    case 'sr':
                      return styles.srCard;
                    default:
                      return styles.srCard;
                  }
                };

                return (
                  <div key={member.id || index} className={`${styles.memberCard} ${getCardStyle(member.level)} ${selectedType === "vip" && goodsPayInfo?.id === member.id ? styles.selected : ""}`}
                       onClick={() => {
                         setSelectedType("vip");
                         setGoodsPayInfo({
                           id: member.id,
                           title: member.title || member.name,
                           price: member.price,
                           type: 2 // 限时会员数据，type应该是2
                         });
                       }}
                  >
                    <div className={styles.memberHeader}>
                      <div className={styles.memberPrice}>
                        <span className={styles.priceAmount}>¥{member.price || 0}</span>
                        <span className={styles.priceUnit}>/月</span>
                      </div>
                      <div className={styles.memberInfo}>
                        <h3 className={styles.memberTitle}>{member.title || member.name || '会员'}</h3>
                        <p className={styles.memberDesc}>{member.description || '无限使用以下模型'}</p>
                        <div className={styles.modelTags}>
                          {member.benefits && Array.isArray(member.benefits) ? (
                            member.benefits.map((benefit, benefitIndex) => (
                              <span key={benefitIndex} className={styles.modelTag}>
                                {benefit}
                              </span>
                            ))
                          ) : (
                            <span className={styles.modelTag}>模型 A</span>
                          )}
                        </div>
                      </div>
                    </div>
                    <button
                      className={styles.memberButton}
                      onClick={() => {
                        const goodsInfo = {
                          id: member.id,
                          title: member.title || member.name,
                          price: member.price,
                          type: 2, // 限时会员数据，type应该是2
                          is_opened: member.is_opened
                        };
                        setSelectedType("vip");
                        setGoodsPayInfo(goodsInfo);
                        setTimeout(() => {
                          hanldePay({ key: payMethod, goods_id: member.id, selectedType: "vip", goodsPayInfo: goodsInfo });
                        }, 0);
                      }}
                    >
                      购买
                    </button>
                  </div>
                );
              })
            ) : (
              <div className={styles.loadingText}>
                加载中... (数据长度: {memberLevel.length})
              </div>
            )}
          </div>
        </div>

        {/* 支付方式选择 */}
        <div className={styles.rechargeSection}>
          <h2 className={styles.sectionTitle}>选择支付方式</h2>
          <div className={styles.paymentOptions}>
            <div
                className={`${styles.paymentOption} ${payMethod === "hupijiao_wx" ? styles.selected : ""
                }`}
                onClick={() => setPayMethod("hupijiao_wx")}
            >
              <div className={styles.paymentLeft}>
                <div className={styles.paymentIcon}>
                  <ChatCheckOutline className={styles.wxIcon} />
                </div>
                <div className={styles.paymentInfo}>
                  <div className={styles.paymentName}>微信支付</div>
                </div>
              </div>
              <div
                  className={`${styles.paymentRadio} ${payMethod === "hupijiao_wx" ? styles.selected : ""
                  }`}
              />
            </div>

            {/*<div*/}
            {/*    className={`${styles.paymentOption} ${payMethod === "taobao" ? styles.selected : ""*/}
            {/*    }`}*/}
            {/*    onClick={() => setPayMethod("taobao")}*/}
            {/*>*/}
            {/*  <div className={styles.paymentLeft}>*/}
            {/*    <div className={styles.paymentIcon}>*/}
            {/*      <HandPayCircleOutline className={styles.tbIcon} />*/}
            {/*    </div>*/}
            {/*    <div className={styles.paymentInfo}>*/}
            {/*      <div className={styles.paymentName}>淘宝支付</div>*/}
            {/*    </div>*/}
            {/*  </div>*/}
            {/*  <div*/}
            {/*      className={`${styles.paymentRadio} ${payMethod === "taobao" ? styles.selected : ""*/}
            {/*      }`}*/}
            {/*  />*/}
            {/*</div>*/}
          </div>
        </div>

        {/* 充值须知 */}
        <div className={styles.rechargeSection}>
          <h2 className={styles.sectionTitle}>充值须知</h2>
          {renderRechargeInstruction()}
        </div>
      </div>

      <Modal
          visible={visible}
          content={
            <div
                className={styles.vipContent}
                dangerouslySetInnerHTML={{ __html: vipContent }}
            />
          }
          showCloseButton={true}
          onClose={() => {
            setVisible(false);
          }}
      />
      <Modal
          visible={payVisible}
          content={<p style={{ textAlign: "center" }}>支付</p>}
          closeOnAction={true}
          closeOnMaskClick={true}
          showCloseButton={true}
          onClose={() => {
            setPayVisible(false);
          }}
          onAction={(action) => hanldePay(action)}
          actions={[
            {
              key: "hupijiao_wx",
              text: (
                  <p className={styles.payItemWrapper}>
                    <ChatCheckOutline fontSize={20} />
                    <span>微信支付</span>
                  </p>
              ),
              primary: true,
            },
            {
              key: "taobao",
              text: (
                  <p className={styles.payItemWrapper}>
                    <HandPayCircleOutline fontSize={20} />
                    <span>淘宝支付</span>
                  </p>
              ),
              primary: true,
            },
          ]}
      />
    </div>
  );
};

export default My;